<!DOCTYPE html>
<html>

	<head>
		<meta charset="UTF-8">
		<title>ex_04</title>

		<script type="text/javascript">
			//需求：为所有的li节点添加onclick响应函数
			//实现city子节点和game子节点对应位置的元素互换
			window.onload = function() {
				//1.获取所有的li节点
				var liNodes = document.getElementsByTagName("li");
				//2.为每一个li节点添加onclick响应函数
				for(var i = 0; i < liNodes.length; i++) {
					liNodes[i].index = i;
					liNodes[i].onclick = function() {

						//alert("index："+this.index);

						//3.找到和当前节点对应的那个li节点
						var targetIndex = 0;
						if(this.index < 4) {
							targetIndex = this.index + 4;
						} else {
							targetIndex = this.index - 4;
						}

						//交换index属性.
						var tempIndex = this.index;
						this.index = liNodes[targetIndex].index;
						liNodes[targetIndex].index = tempIndex;

						//alert(liNodes[targetIndex].firstChild.nodeValue);
						//4.互换
						replaceEach(this, liNodes[targetIndex]);
					}
				}

			}

			function replaceEach(aNode, bNode) {
				//1.获取aNode和bNode的父节点，使用parentNode属性
				var aParent = aNode.parentNode;
				var bParent = bNode.parentNode;

				if(aParent && bParent) {
					//2.克隆aNode或bNode
					var aNode2 = aNode.cloneNode(true);

					//克隆aNode的同时，把onclick事件也复制.
					aNode2.onclick = aNode.onclick;
					//克隆aNode的同时，把index事件也复制.
					aNode2.index = aNode.index;

					//3.分别调用aNode的父节点和bNode的父节点的replaceChild()方法实现节点的互换
					bParent.replaceChild(aNode2, bNode);
					aParent.replaceChild(bNode, aNode);
				}

			}
		</script>

	</head>

	<body>
		<p>你喜欢哪个城市？</p>
		<ul id="city">
			<li id="bj" name="BeiJing">北京</li>
			<li>上海</li>
			<li>东京</li>
			<li>首尔</li>
		</ul>
		<br/><br/>
		<p>你喜欢哪款单机游戏</p>
		<ul id="game">
			<li id="rl">红警</li>
			<li>实况</li>
			<li>极品飞车</li>
			<li>魔兽</li>
		</ul>
		<br /><br /> gender:
		<input type="radio" name="gender" id="gender" value="male" />Male
		<input type="radio" name="gender" id="gender" value="female" />Female

		<br/><br/> name:
		<input type="text" name="username" id="name" value="idea" />
	</body>

</html>